from django.shortcuts import render, HttpResponse, redirect
from app01 import models
from app01.utils.bootstrap import BootStrapFrom, BootStrapModelFrom


def city_list(request):
    """城市"""
    queryset = models.City.objects.all()

    return render(request, 'city_list.html', {'queryset': queryset})


class UpModelForm(BootStrapModelFrom):
    bootstrap_exclude_fields = ['img']

    class Meta:
        model = models.City
        fields = "__all__"


def city_add(request):
    """城市新建"""
    title = "新建城市"
    if request.method == 'GET':
        form = UpModelForm()
        return render(request, 'upload_form.html', {
            'form': form,
            'title': title
        })

    form = UpModelForm(data=request.POST, files=request.FILES)
    # app01 / views / city.py
    if form.is_valid():
        # 对于文件操作 自动保存
        # 字段 + 上传的路径写入数据库
        form.save()
        # 成功返回到列表
        return redirect('/city/list/')

    return render(request, 'upload_form.html', {
        'form': form,
        'title': title
    })
